package s63.kong.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import s63.kong.shop.pojo.Dept;
import s63.kong.shop.service.DeptService;
import s63.kong.shop.mapper.DeptMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService{
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;


    @SneakyThrows//表示在方法内部自动捕获并处理异常
    @Override
    public List<Dept> selectAll() {
        List<Dept> deptList;
        String json = stringRedisTemplate.opsForValue().get("kong:dept");//先从Redis中获取名为"kong:dept"的字符串类型值
        if (StringUtils.hasText(json)){//如果值存在
            deptList = objectMapper.readValue(json,List.class);//将其转换为Dept类型的List集合
        }else {
            deptList = getBaseMapper().selectAll();//调用父类的selectAll方法获取Dept类型的List集合
            //将其转换为JSON字符串后存储到Redis中
            stringRedisTemplate.opsForValue().set("kong:dept", objectMapper.writeValueAsString(deptList));
        }
        return deptList;//最后返回Dept类型的List集合。
    }
}




